#coding=utf8

import sys
import logging

import click

from pake.pakefile import Pakefile
from pake.exceptions import *
from pake.utils import ColordLogger


@click.command()
@click.option('-v', 'verbose', is_flag=True, help=u'开启运行时log')
@click.option('-t', 'test', is_flag=True, help=u'测试命令，不实际运行')
@click.option('-d', 'dump', is_flag=True, help=u'打印所有命令')
@click.argument('name', required=False)
@click.argument('argument', nargs=-1)
def cli(verbose, test, dump, name, argument):
    ColordLogger.level = logging.DEBUG if verbose else logging.INFO
    ColordLogger.info('[start] verbose=%s, test=%s, dump=%s, name=%s, argument=%s' % (verbose, test, dump, name, argument))

    if name is None:
        name = 'default'

    packfile = Pakefile(test=test)
    try:
        packfile.parse('Makefile')
    except IOError as e:
        ColordLogger.error(u'文件不存在或没有权限：{}'.format(e))
        sys.exit(-1)
    except CompileError as e:
        ColordLogger.error(u'文件解析失败：{}'.format(e.message))
        sys.exit(-1)

    if dump:
        packfile.dump()
        sys.exit(0)

    extra = ','.join(argument)
    try:
        packfile.execute(name, extra)
    except CommandNotFound as e:
        ColordLogger.error(u'%s', e)
    except ExecuteError as e:
        ColordLogger.error(u'%s', e)


def main():
    cli()


if __name__ == '__main__':
    main()
